import re
import uuid
import datetime
from binascii import a2b_hex
from Crypto.Cipher import AES

aesKey = b'2024052020240520'  # 加密与解密所使用的密钥，长度必须是16的倍数
aesIv = b'2024052020240520'  # initial Vector,长度要与aesKey一致
aesMode = AES.MODE_CBC  # 使用CBC模式


class LicenseCheck():
    def start_check(self):
        """ 开始检验license """

        license_dic = self.parse_license_file()
        sign = self.decrypt(license_dic['Sign'])

        sign_list = sign.split('#')
        mac = sign_list[0].strip()
        date = sign_list[1].strip()

        # 校验license文件MAC地址和Date是否被手动更改
        if (mac != license_dic['MAC']) or (date != license_dic['Date']):
            return {'code': '0', 'msg': '*License Error*: License file is modified!'}

        if len(sign_list) == 2:
            mac = self.get_mac()  # 获取服务器MAC地址
            current_date = datetime.datetime.now().strftime('%Y%m%d')  # 获取当前时间

            # 校验物理地址是否正确
            if sign_list[0] != mac:
                return {'code': '0', 'msg': '*License Error*: Invalid host!'}

            # 检验license文件是否过期
            if sign_list[1] <= current_date:
                return {'code': '0', 'msg': '*License Error*: License is expired!'}

        else:
            print('*License Error*: Wrong Sign setting on license file.')
            return {'code': '0', 'msg': '*License Error*: Wrong Sign setting on license file.'}

    def parse_license_file(self):
        """ 解析license文件 """
        license_dic = {}
        license_file = 'License.dat'

        try:
            with open(license_file, 'r') as LF:
                for line in LF.readlines():
                    if re.match('^\s*(\S+)\s*:\s*(\S+)\s*$', line):
                        my_match = re.match('^\s*(\S+)\s*:\s*(\S+)\s*$', line)
                        license_dic[my_match.group(1)] = my_match.group(2)
        except Exception as e:
            return {'code': '0', 'msg': '*License Error*: License文件不存在.', 'data': str(e)}

        return (license_dic)

    def decrypt(self, content):
        """ 解密license文件 """
        aes = AES.new(aesKey, aesMode, aesIv)
        decrypted_content = aes.decrypt(a2b_hex(content.encode('utf-8')))

        return decrypted_content.decode('utf-8')

    def get_mac(self):
        """ 获取服务器MAC地址 """
        mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
        return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])


if __name__ == '__main__':
    license_check_obj = LicenseCheck()
    mac = license_check_obj.get_mac()
    print(mac)
    res_data = license_check_obj.start_check()
    if res_data and res_data.get('code') == '0':
        print({"code": 0, "msg": res_data.get('msg', ''), "data": res_data.get('data', '')})
    else:
        print("license授权成功, 开始执行业务流程")
